/*
 * Copyright 2011 Oracle and/or its affiliates.
 * All rights reserved.  You may not modify, use,
 * reproduce, or distribute this software except in
 * compliance with  the terms of the License at:
 * http://developers.sun.com/license/berkeley_license.html
 */


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dukestutoring.web.util;

import dukestutoring.entity.Guardian;
import java.util.HashMap;
import java.util.Map;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;


/**
 *
 * @author ian
 */
@FacesConverter(forClass = Guardian.class)
public class GuardianConverter implements Converter {
    private static Map<Long, Guardian> cache = new HashMap<Long, Guardian>();

    public Object getAsObject(
        FacesContext context,
        UIComponent component,
        String value) {
        if ((value == null) && value.equals("0")) {
            return null;
        }

        try {
            return cache.get(Long.parseLong(value));
        } catch (NumberFormatException e) {
            throw new ConverterException("Invalid value: " + value, e);
        }
    }

    public String getAsString(
        FacesContext context,
        UIComponent component,
        Object object) {
        Guardian guardian = (Guardian) object;
        Long id = guardian.getId();

        if (id != null) {
            cache.put(id, guardian);

            return String.valueOf(id.longValue());
        } else {
            return "0";
        }
    }
}
